package com.quzhi.sys.controller.warehouseController;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.quzhi.common.Result;
import com.quzhi.sys.entity.GoodsType;
import com.quzhi.sys.entity.Product;
import com.quzhi.sys.entity.User;
import com.quzhi.sys.service.impl.GoodsTypeServiceImpl;
import com.quzhi.sys.service.impl.ProductServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器 商品分类
 * </p>
 *
 * @author Xibing
 * @since 2024-07-23
 */
@RestController
@RequestMapping("/sys/goodsType")
public class GoodsTypeController {
    @Autowired
    private GoodsTypeServiceImpl goodsTypeService;

    @Autowired
    private ProductServiceImpl productService;

    @PostMapping
    public Result<?> addType(@RequestBody GoodsType goodsType){
        // 查询该分类是否存在
        GoodsType byId = goodsTypeService.getById(goodsType);
        if(byId == null){
            goodsType.setId(UUID.randomUUID().toString());
            goodsType.setCreateTime(LocalDateTime.now());
            goodsType.setUpdateTime(LocalDateTime.now());

            goodsTypeService.save(goodsType);
            return Result.success("添加成功");

        }else{
            return Result.fail(20002,"该分类已存在");
        }
    }


    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable("id") String id){
        GoodsType byId = goodsTypeService.getById(id);
        return Result.success(byId);
    }

    @GetMapping("/list")
    public Result<?> getList(){
        List<GoodsType> list = goodsTypeService.list();
        return Result.success(list);
    }

    @DeleteMapping("/{id}")
    public Result<?> deleteById(@PathVariable("id") String id){
        // 更具id查询商品，如果有商品绑定该分类则不能删除
        LambdaQueryWrapper<Product> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Product::getGoodsTypeId, id);

        List<Product> list = productService.list(wrapper);
        if(list.size() > 0){
            return Result.fail(20002, "删除失败，该分类已绑定商品");
        }

        goodsTypeService.removeById(id);
        return Result.success();
    }

    @PutMapping
    public Result<?> updateById(@RequestBody GoodsType goodsType){

        goodsTypeService.updateById(goodsType);
        return Result.success();
    }

}
